The maps package produces pretty rudimentary maps which you can use for your visualizations. ggmap is the package that you’ll want to use if you want a more detailed map as background to your visualizations. In what follows, we’ll demonstrate how to use ggmap with the Sacramento dataset in the caret package:

library(caret)
library(dplyr)
library(ggmap)

data(Sacramento)
df <- Sacramento %>% group_by(city) %>%
    summarize(median_price = median(price), transactions = n(),
              latitude = mean(latitude), longitude = mean(longitude))

Google maps

It turns out that using Google maps as a background is quite a challenge now. To do so, you need to provide an API key and enable billing. See https://github.com/dkahle/ggmap for more details on how to work with these new restrictions.

Stamen maps

Fortunately there is an easier way to get maps which are more sophisticated than those provided by the maps package: Stamen maps. The code below is an example of how to get a map from Stamen maps (the get_stamenmap function belongs to the ggmap package.)

height <- max(Sacramento$latitude) - min(Sacramento$latitude)
width <- max(Sacramento$longitude) - min(Sacramento$longitude)
sac_borders <- c(bottom  = min(Sacramento$latitude)  - 0.1 * height, 
                 top     = max(Sacramento$latitude)  + 0.1 * height,
                 left    = min(Sacramento$longitude) - 0.1 * width,
                 right   = max(Sacramento$longitude) + 0.1 * width)

map <- get_stamenmap(sac_borders, zoom = 10, maptype = "toner-lite")
## Source : http://tile.stamen.com/toner-lite/10/165/390.png
## Source : http://tile.stamen.com/toner-lite/10/166/390.png
## Source : http://tile.stamen.com/toner-lite/10/167/390.png
## Source : http://tile.stamen.com/toner-lite/10/168/390.png
## Source : http://tile.stamen.com/toner-lite/10/169/390.png
## Source : http://tile.stamen.com/toner-lite/10/165/391.png
## Source : http://tile.stamen.com/toner-lite/10/166/391.png
## Source : http://tile.stamen.com/toner-lite/10/167/391.png
## Source : http://tile.stamen.com/toner-lite/10/168/391.png
## Source : http://tile.stamen.com/toner-lite/10/169/391.png
## Source : http://tile.stamen.com/toner-lite/10/165/392.png
## Source : http://tile.stamen.com/toner-lite/10/166/392.png
## Source : http://tile.stamen.com/toner-lite/10/167/392.png
## Source : http://tile.stamen.com/toner-lite/10/168/392.png
## Source : http://tile.stamen.com/toner-lite/10/169/392.png
## Source : http://tile.stamen.com/toner-lite/10/165/393.png
## Source : http://tile.stamen.com/toner-lite/10/166/393.png
## Source : http://tile.stamen.com/toner-lite/10/167/393.png
## Source : http://tile.stamen.com/toner-lite/10/168/393.png
## Source : http://tile.stamen.com/toner-lite/10/169/393.png
## Source : http://tile.stamen.com/toner-lite/10/165/394.png
## Source : http://tile.stamen.com/toner-lite/10/166/394.png
## Source : http://tile.stamen.com/toner-lite/10/167/394.png
## Source : http://tile.stamen.com/toner-lite/10/168/394.png
## Source : http://tile.stamen.com/toner-lite/10/169/394.png
ggmap(map)

Notice that a bunch of messages are printed showing what files are being loaded. To remove these messages from your report, include the option “message=FALSE” at the top of your R chunk.

By default, the zoom parameter is set to 10. Making it bigger gives a more detailed map, but takes longer to load.

Just like in ggplot2 graphics, we can add layers to the map drawn by ggmap(map) with the + syntax. For example, if we wanted to overlay the map with the data from our Sacramento dataset, we could do the following:

ggmap(map) +
    geom_point(data = df, mapping = aes(x = longitude, y = latitude, 
                                        col = median_price, size = transactions)) +
    scale_color_distiller(palette = "YlOrRd", direction = 1)

Another way to get Stamen maps as a background is to use the qmplot function. Notice though that the syntax is pretty different from what we had with ggplot. Here is a map plotting the same points as above but with a different color scale:

qmplot(x = longitude, y = latitude, data = df, maptype = "watercolor", 
       geom = "point", color = median_price, size = transactions) +
    scale_color_gradient(low = "blue", high = "red")

The full list of map types is “terrain”, “terrain-background”, “terrain-labels”, “terrain-lines”, “toner”, “toner-2010”, “toner-2011”, “toner-background”, “toner-hybrid”, “toner-labels”, “toner-lines”, “toner-lite”, “watercolor”. Note that some of them don’t work with the CRAN version of ggmap (e.g. “terrain”); instead, you will have to download the github version of the package (see https://github.com/dkahle/ggmap/issues/188).

Below are examples of what “terrain” and “toner” look like:

qmplot(x = longitude, y = latitude, data = df, maptype = "terrain", 
       geom = "point", color = median_price, size = transactions) +
    scale_color_gradient(low = "blue", high = "red")

qmplot(x = longitude, y = latitude, data = df, maptype = "toner", 
       geom = "point", color = median_price, size = transactions) +
    scale_color_gradient(low = "blue", high = "red")

Session info

sessionInfo()
## R version 3.5.1 (2018-07-02)
## Platform: x86_64-apple-darwin15.6.0 (64-bit)
## Running under: macOS Sierra 10.12.6
## 
## Matrix products: default
## BLAS: /Library/Frameworks/R.framework/Versions/3.5/Resources/lib/libRblas.0.dylib
## LAPACK: /Library/Frameworks/R.framework/Versions/3.5/Resources/lib/libRlapack.dylib
## 
## locale:
## [1] en_US.UTF-8/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8
## 
## attached base packages:
## [1] stats     graphics  grDevices utils     datasets  methods   base     
## 
## other attached packages:
## [1] bindrcpp_0.2.2  ggmap_2.7.900   dplyr_0.7.7     caret_6.0-80   
## [5] ggplot2_3.0.0   lattice_0.20-35
## 
## loaded via a namespace (and not attached):
##  [1] magic_1.5-9        ddalpha_1.3.4      tidyr_0.8.1       
##  [4] sfsmisc_1.1-2      splines_3.5.1      foreach_1.4.4     
##  [7] prodlim_2018.04.18 assertthat_0.2.0   stats4_3.5.1      
## [10] DRR_0.0.3          yaml_2.1.19        robustbase_0.93-3 
## [13] ipred_0.9-7        pillar_1.3.0       backports_1.1.2   
## [16] glue_1.3.0         digest_0.6.18      RColorBrewer_1.1-2
## [19] colorspace_1.3-2   recipes_0.1.3      htmltools_0.3.6   
## [22] Matrix_1.2-14      plyr_1.8.4         timeDate_3043.102 
## [25] pkgconfig_2.0.2    CVST_0.2-2         broom_0.5.0       
## [28] purrr_0.2.5        scales_1.0.0       jpeg_0.1-8        
## [31] gower_0.1.2        lava_1.6.3         tibble_1.4.2      
## [34] withr_2.1.2        nnet_7.3-12        lazyeval_0.2.1    
## [37] survival_2.42-3    magrittr_1.5       crayon_1.3.4      
## [40] evaluate_0.10.1    nlme_3.1-137       MASS_7.3-50       
## [43] dimRed_0.1.0       class_7.3-14       tools_3.5.1       
## [46] data.table_1.11.4  RgoogleMaps_1.4.2  stringr_1.3.1     
## [49] kernlab_0.9-27     munsell_0.5.0      pls_2.6-0         
## [52] compiler_3.5.1     RcppRoll_0.3.0     rlang_0.2.2       
## [55] grid_3.5.1         iterators_1.0.10   rjson_0.2.20      
## [58] labeling_0.3       bitops_1.0-6       rmarkdown_1.10    
## [61] geometry_0.3-6     gtable_0.2.0       ModelMetrics_1.2.0
## [64] codetools_0.2-15   abind_1.4-5        reshape2_1.4.3    
## [67] R6_2.3.0           lubridate_1.7.4    knitr_1.20        
## [70] bindr_0.1.1        rprojroot_1.3-2    stringi_1.2.3     
## [73] Rcpp_0.12.19       rpart_4.1-13       png_0.1-7         
## [76] DEoptimR_1.0-8     tidyselect_0.2.5